package cn.dzhang.spring.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import cn.dzhang.spring.model.User;
import cn.dzhang.spring.repository.UserRepository;
import cn.dzhang.spring.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {
	private static final Log log = LogFactory.getLog(UserServiceImpl.class);
	@Resource
	private UserRepository ur;

	public List<User> findByName(String name) {
		return ur.findByName(name);
	}

	public User findByUsername(String username) {
		return ur.findByUsername(username);
	}

	@Override
	public List<User> findAll() {
		List<User> users = ur.findAll();
		return users;
	}

	@Override
	public User saveOrUpdate(User user) {
		User result = ur.saveAndFlush(user);
		return result;
	}

	public boolean delete(User user) {
		try {
			ur.delete(user);
		} catch (Exception e) {
			log.error("删除用户失败", e);
			return false;
		}

		return true;
	}

	public boolean deleteById(String id) {
		return delete(ur.findOne(id));
	}

	public User findById(String id) {
		return ur.findOne(id);
	}

	public boolean exists(String name) {
		return null != ur.findByName(name);
	}
}
